package com.fangque.kepp.framework.util;

import com.alibaba.fastjson.JSON;
import com.fangque.kepp.framework.user.entity.UserToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lan
 * @date 2019/4/8 14:19
 */
@Component
@ConfigurationProperties(prefix = "kepp.jwt")
@Data
public class JwtTokenUtil {

    /**
     * header名称
     */
    private String tokenHeader = "Authorization";

    /**
     * token前缀
     */
    private String tokenPrefix = "Bearer";

    /**
     * 秘钥
     */
    private String secret = "kepp";

    /**
     * 过期时间 (默认1小时)
     */
    private Long expiration = 3600L;

    /**
     * 选择记住后过期时间
     */
    private Long rememberExpiration = 604800L;

    private String[] allowUrl;

    /**
     * 生成token
     *
     * @param userToken 用户名称和权限表
     * @return jwt
     */
    public String createToken(UserToken userToken) {
        Long time = this.expiration;
//        Long time = user.getRemember() ? this.rememberExpiration : this.expiration;
        Map<String, Object> map = new HashMap<>(1);
        map.put("userToken", userToken);
        return Jwts.builder()
                .setClaims(map)
                .setSubject(userToken.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + time * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取用户名
     *
     * @param token
     * @return
     */
    public String getUserName(String token) {
        return generateToken(token).getSubject();
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Claims generateToken(String token) {

        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取userDTO
     *
     * @param token
     * @return
     */
    public UserToken getUserDTO(String token) {
        Claims claims = generateToken(token);
        // 此处无法直接返回 Authorities, 需要先返回role后拼接
        Map<String, Object> map = claims.get("userToken", Map.class);
        return JSON.parseObject(JSON.toJSONString(map), UserToken.class);
    }
}